package com.ljkj.cordial.chat.dao;

import android.text.TextUtils;

import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.CollectionUtils;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.ui.ChatUtils;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.util.ObserverThread;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Transient;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 会话表
 */
@Entity(nameInDb = "ChatTableBean")
public class ChatTableBean implements Serializable {
    private static final long serialVersionUID = 4049232129637634268L;
    public final static int SEND = 0;
    public final static int RECEIVE = 1;
    public final static int SEND_ING = 0;
    public final static int SEND_SUCCESS = 1;
    public final static int SEND_FAIL = 2;
    public final static int UNREAD = 0;
    public final static int READED = 1;
    public final static int UNLISTEN = 1;
    public final static int LISTENED = 0;
    @Id(autoincrement = true)
    private Long id;
    /**
     * 单聊(Canstants.SINGLE_CHAT)、群聊
     */
    @Property(nameInDb = "FROM_TYPE")
    private int fromType;
    @Property(nameInDb = "GROUP_ID")
    private String groupId;
    /**
     * 群类别注册群游客群
     */
    @Property(nameInDb = "GROUP_TYPE")
    private String groupType;
    /**
     * friendId,memberId
     */
    @Property(nameInDb = "TARGET_FILE_ID")
    private String targetFileId;
    @Property(nameInDb = "TARGET_ID")
    private String targetId;
    @Property(nameInDb = "TARGET_NAME")
    private String targetName;
    @Property(nameInDb = "TARGET_TYPE")
    private String targetType;
    @Property(nameInDb = "NICK_NAME")
    private String nickName;
    @Property(nameInDb = "ALIAS")//备注
    private String alias;
    @Property(nameInDb = "TARGET_AVATAR_URL")
    private String chatAvatarUrl;
    @Property(nameInDb = "TARGET_AVATAR_ID")
    private String chatAvatarPath;
    @Property(nameInDb = "TARGET_AVATAR_Path")//用作语音时长字段
    private String chatAvatarId;
    @Property(nameInDb = "CHAT_TYPE")
    private int chatType;
    @Property(nameInDb = "CHAT_UNREAD")//1已读0未读
    private int chatUnRead;
    @Property(nameInDb = "HISTORY_TIME")
    private long historyTime;
    @Property(nameInDb = "MSG_TIME")
    private long msgTime;
    @Property(nameInDb = "TEXT_MSG")
    private String textMsg;
    @Property(nameInDb = "FILE_URL")//文件地址
    private String fileUrl;
    @Property(nameInDb = "THUMB_PATH")//缩略路径
    private String thumbPath;
    @Property(nameInDb = "FILE_LENGTH")//文件大小
    private long fileLength;
    @Property(nameInDb = "ALBUM_ID")//文件id
    private String albumId;
    @Property(nameInDb = "SEND_TYPE")//文件id
    private int sendType;//0发送者1接收者
    @Property(nameInDb = "MSG_ID")
    private String msgId;
    @Property(nameInDb = "LOGIN_USER_ID")
    private String loginUserId;
    @Property(nameInDb = "CHAT_NAME")//会话名称，好友id或群组id
    private String chatName;
    @Property(nameInDb = "START_READ_FINISH")
    private boolean startReadFinish;//是否开启阅后即焚
    @Property(nameInDb = "READ_FINISH_TIME")
    private long readFinishTime;////阅后即焚时间s
    @Property(nameInDb = "SEND_STATE")
    private int sendState;//0发送中1发送成功2发送失败
    @Property(nameInDb = "VOICE_LISTEN")//语音 1已读0未读
    private int voiceListen = UNLISTEN;
    @Property(nameInDb = "RELATE_ID")//关联ID，目前用于和时间Id关联
    private Long relateId;
    @Property(nameInDb = "ATEL_IDS")
    private String atelIds;
    //    @Convert(converter = TextCharSequenceTran.class, columnType = String.class)
//    private TextCharSequenceTran charSequenceText;
    @Transient
    private boolean isChecked;//多选框状态
    @Transient
    private boolean isVisible;//是否显示多选框


    public int getSendState() {
        return sendState;
    }

    public void setSendState(int sendState) {
        this.sendState = sendState;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }

    public boolean isVisible() {
        return isVisible;
    }

    public void setVisible(boolean visible) {
        isVisible = visible;
    }

    @Generated(hash = 514463719)
    public ChatTableBean(Long id, int fromType, String groupId, String groupType, String targetFileId, String targetId, String targetName, String targetType, String nickName, String alias, String chatAvatarUrl, String chatAvatarPath, String chatAvatarId,
                         int chatType, int chatUnRead, long historyTime, long msgTime, String textMsg, String fileUrl, String thumbPath, long fileLength, String albumId, int sendType, String msgId, String loginUserId, String chatName, boolean startReadFinish,
                         long readFinishTime, int sendState, int voiceListen, Long relateId, String atelIds) {
        this.id = id;
        this.fromType = fromType;
        this.groupId = groupId;
        this.groupType = groupType;
        this.targetFileId = targetFileId;
        this.targetId = targetId;
        this.targetName = targetName;
        this.targetType = targetType;
        this.nickName = nickName;
        this.alias = alias;
        this.chatAvatarUrl = chatAvatarUrl;
        this.chatAvatarPath = chatAvatarPath;
        this.chatAvatarId = chatAvatarId;
        this.chatType = chatType;
        this.chatUnRead = chatUnRead;
        this.historyTime = historyTime;
        this.msgTime = msgTime;
        this.textMsg = textMsg;
        this.fileUrl = fileUrl;
        this.thumbPath = thumbPath;
        this.fileLength = fileLength;
        this.albumId = albumId;
        this.sendType = sendType;
        this.msgId = msgId;
        this.loginUserId = loginUserId;
        this.chatName = chatName;
        this.startReadFinish = startReadFinish;
        this.readFinishTime = readFinishTime;
        this.sendState = sendState;
        this.voiceListen = voiceListen;
        this.relateId = relateId;
        this.atelIds = atelIds;
    }

    @Generated(hash = 1057574713)
    public ChatTableBean() {
    }


    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getFromType() {
        return this.fromType;
    }

    public void setFromType(int fromType) {
        this.fromType = fromType;
    }

    public String getGroupId() {
        return this.groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getTargetId() {
        return this.targetId;
    }

    public void setTargetId(String targetId) {
        this.targetId = targetId;
    }

    public String getTargetName() {
        return this.targetName;
    }

    public void setTargetName(String targetName) {
        this.targetName = targetName;
    }

    public String getTargetType() {
        return this.targetType;
    }

    public void setTargetType(String targetType) {
        this.targetType = targetType;
    }

    public String getNickName() {
        return this.nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getChatAvatarUrl() {
        return this.chatAvatarUrl;
    }

    public void setChatAvatarUrl(String chatAvatarUrl) {
        this.chatAvatarUrl = chatAvatarUrl;
    }

    public String getChatAvatarId() {
        return this.chatAvatarId;
    }

    public void setChatAvatarId(String chatAvatarId) {
        this.chatAvatarId = chatAvatarId;
    }

    public int getChatType() {
        return this.chatType;
    }

    public void setChatType(int chatType) {
        this.chatType = chatType;
    }

    public int getChatUnRead() {
        return this.chatUnRead;
    }

    public void setChatUnRead(int chatUnRead) {
        this.chatUnRead = chatUnRead;
    }

    public long getHistoryTime() {
        return this.historyTime;
    }

    public void setHistoryTime(long historyTime) {
        this.historyTime = historyTime;
    }

    public long getMsgTime() {
        return this.msgTime;
    }

    public void setMsgTime(long msgTime) {
        this.msgTime = msgTime;
    }

    public String getTextMsg() {
        return this.textMsg;
    }

    public void setTextMsg(String textMsg) {
        this.textMsg = textMsg;
    }

    public String getFileUrl() {
        return this.fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public String getAlbumId() {
        return this.albumId;
    }

    public void setAlbumId(String albumId) {
        this.albumId = albumId;
    }

    public int getSendType() {
        return this.sendType;
    }

    public void setSendType(int sendType) {
        this.sendType = sendType;
    }

    public String getMsgId() {
        return this.msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }

    public boolean isStartReadFinish() {
        return startReadFinish;
    }

    public void setStartReadFinish(boolean startReadFinish) {
        this.startReadFinish = startReadFinish;
    }

    public long getReadFinishTime() {
        return readFinishTime;
    }

    public long getReadFinishSpaceTime() {
        long s = (getMsgTime() + getReadFinishTime() * 1000 - System.currentTimeMillis());
//        JLog.e(getStartReadFinish()+"read finish space time"+s);
        return s;
    }

    public String getReadFinishFormatTime() {
//        getReadFinishTime() * 1000
        return AlbumManageUtil.generateTime(getReadFinishSpaceTime());
    }

    public void setReadFinishTime(long readFinishTime) {
        this.readFinishTime = readFinishTime;
    }

    public static long insert(ChatTableBean bean) {
        if (bean.getId() != null) {
            DbController.getInstance().getWrite().update(bean);
            return bean.getId();
        }
        bean.setLoginUserId(ChatApp.getInstance().getUserId());
        return DbController.getInstance().getWrite().insertOrReplace(bean);
    }

    public static void insertWithNewMsgID(ChatTableBean bean) {
        bean.setLoginUserId(ChatApp.getInstance().getUserId());
        long id = DbController.getInstance().getWrite().getChatTableBeanDao().insertOrReplace(bean);
        long count;
        do {
            bean.setMsgTime(System.currentTimeMillis());
            bean.setHistoryTime(System.currentTimeMillis());
            bean.setMsgId(ChatUtils.createMessageId(id, UserPreferences.getUserId(), bean.getChatName(), bean.getMsgTime()));
            count = DbController.getInstance().getRead()
                    .getChatTableBeanDao().queryBuilder().where(
                            ChatTableBeanDao.Properties.MsgId.eq(bean.getMsgId()),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                    .count();
        } while (count > 0);
        DbController.getInstance().getWrite().getChatTableBeanDao().update(bean);
    }


    public synchronized static long insertWhenMsgIdNotExist(ChatTableBean bean) {
        ChatTableBean tableFromMsgId = queryNewFriendMsg(bean.getTargetId(), bean.getMsgId());
        if (tableFromMsgId == null)
            tableFromMsgId = new ChatTableBean();
        tableFromMsgId.setMsgId(bean.getMsgId());
        tableFromMsgId.setAtelIds(bean.getAtelIds());
        tableFromMsgId.setAlbumId(bean.getAlbumId());
        tableFromMsgId.setThumbPath(bean.getThumbPath());
        tableFromMsgId.setVoiceListen(bean.getVoiceListen());
        tableFromMsgId.setReadFinishTime(bean.getReadFinishTime());
        tableFromMsgId.setChatAvatarId(bean.getChatAvatarId());
        tableFromMsgId.setChatAvatarUrl(bean.getChatAvatarUrl());
        tableFromMsgId.setChatAvatarPath(bean.getChatAvatarPath());
        tableFromMsgId.setChatType(bean.getChatType());
        tableFromMsgId.setFileUrl(bean.getFileUrl());
        tableFromMsgId.setTargetId(bean.getTargetId());
        tableFromMsgId.setStartReadFinish(bean.getStartReadFinish());
        tableFromMsgId.setSendState(bean.getSendState());
        tableFromMsgId.setMsgTime(bean.getMsgTime());
        tableFromMsgId.setAlias(bean.getAlias());
        tableFromMsgId.setChatName(bean.getChatName());
        tableFromMsgId.setChatUnRead(bean.getChatUnRead());
        tableFromMsgId.setChecked(bean.isChecked());
        tableFromMsgId.setFileLength(bean.getFileLength());
        tableFromMsgId.setFromType(bean.getFromType());
        tableFromMsgId.setGroupId(bean.getGroupId());
        tableFromMsgId.setGroupType(bean.getGroupType());
        tableFromMsgId.setHistoryTime(bean.getHistoryTime());
        tableFromMsgId.setNickName(bean.getNickName());
        tableFromMsgId.setRelateId(bean.getRelateId());
        tableFromMsgId.setSendType(bean.getSendType());
        tableFromMsgId.setTargetFileId(bean.getTargetFileId());
        tableFromMsgId.setTargetName(bean.getTargetName());
        tableFromMsgId.setTargetType(bean.getTargetType());
        tableFromMsgId.setTextMsg(bean.getTextMsg());
        tableFromMsgId.setVisible(bean.isVisible());
        tableFromMsgId.setLoginUserId(ChatApp.getInstance().getUserId());
        DbController.getInstance().getWrite().getChatTableBeanDao().save(tableFromMsgId);
        return tableFromMsgId.getId();

//        bean.setLoginUserId(ChatApp.getInstance().getUserId());
//        ChatTableBean tableFromMsgId = getTableFromMsgId(bean.getMsgId());
//        if (tableFromMsgId == null) {
//            DbController.getInstance().getWrite().getChatTableBeanDao().save(bean);
//        } else {
//            return tableFromMsgId.getId();
//        }
//
//        return bean.getId();

//        if (bean.getId() != null) {
//            DbController.getInstance().getWrite().update(bean);
//            return bean.getId();
//        }
//        bean.setLoginUserId(ChatApp.getInstance().getUserId());
//        ChatTableBean tableFromMsgId = getTableFromMsgId(bean.getMsgId());
//        if (tableFromMsgId == null) {
//            return DbController.getInstance().getWrite().insertOrReplace(bean);
//        } else {
//            bean.setId(tableFromMsgId.getId());
//            DbController.getInstance().getWrite().update(bean);
//            return bean.getId();
//        }
    }

    public static long insertOnly(ChatTableBean bean) {
        bean.setLoginUserId(ChatApp.getInstance().getUserId());
        return DbController.getInstance().getWrite().getChatTableBeanDao().insertOrReplace(bean);

    }

    /**
     * 通过msgId获取table
     *
     * @param msgId
     * @return
     */
    public static ChatTableBean getTableFromMsgId(String msgId) {
        try {
            return DbController.getInstance().getRead().getChatTableBeanDao()
                    .queryBuilder().where(ChatTableBeanDao.Properties.MsgId.eq(msgId)
                            , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).unique();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 通过id获取table
     *
     * @param id
     * @return
     */
    public static ChatTableBean getTableFromId(String id) {
        ChatTableBean u = null;
        try {
            u = DbController.getInstance().getRead().getChatTableBeanDao()
                    .queryBuilder().where(ChatTableBeanDao.Properties.Id.eq(id)).unique();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return u;
        }
    }

    /**
     * limit 在分页过程不可变
     *
     * @param fromType
     * @param targetId
     * @param id       friendUserId or groupId
     * @return
     */
    public static List<ChatTableBean> query(int fromType, String targetId, String id, int offset, int limit) {
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        if (fromType == Canstants.GROUP_CHAT) {
            return cDao.queryBuilder()
                    .orderDesc(ChatTableBeanDao.Properties.HistoryTime)
                    .where(
                            ChatTableBeanDao.Properties.ChatName.eq(id),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT)
                            , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(
//                            ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
//                            , ChatTableBeanDao.Properties.GroupId.eq(targetId))
//
                    .offset(offset * limit).limit(limit)
                    .list();

        } else {
            return cDao
                    .queryBuilder()
                    .orderDesc(ChatTableBeanDao.Properties.HistoryTime)
                    .where(
                            ChatTableBeanDao.Properties.ChatName.eq(id),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
//                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .offset(offset * limit).limit(limit).list();
        }
    }

    public static boolean hasUnreadAt(int fromType, String targetId) {
        List<ChatTableBean> unreadAtList = null;
        if (fromType == Canstants.GROUP_CHAT) {
            unreadAtList = DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                    .where(ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT),
                            ChatTableBeanDao.Properties.GroupId.eq(targetId),
                            ChatTableBeanDao.Properties.ChatUnRead.eq(UNREAD),
                            ChatTableBeanDao.Properties.SendType.eq(RECEIVE),
                            ChatTableBeanDao.Properties.AtelIds.like("%" + UserPreferences.getUserId() + "%"),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                    .list();
        } else {
            unreadAtList = DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                    .where(ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                            ChatTableBeanDao.Properties.TargetId.eq(targetId),
                            ChatTableBeanDao.Properties.ChatUnRead.eq(UNREAD),
                            ChatTableBeanDao.Properties.SendType.eq(RECEIVE),
                            ChatTableBeanDao.Properties.AtelIds.like("%" + UserPreferences.getUserId() + "%"),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                    .list();
        }
        return !CollectionUtils.isEmpty(unreadAtList);
    }

    public static List<ChatTableBean> query(String groupId, String targetId) {
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        if (!TextUtils.isEmpty(groupId)) {
            return cDao.queryBuilder().where(
                    ChatTableBeanDao.Properties.ChatName.eq(groupId),
                    ChatTableBeanDao.Properties.GroupId.eq(groupId)
                    , ChatTableBeanDao.Properties.TargetId.eq(targetId)
                    , ChatTableBeanDao.Properties.TargetId.notEq(ChatApp.getInstance().getUserId())).list();
        }

        return cDao.queryBuilder().where(
                ChatTableBeanDao.Properties.ChatName.eq(targetId)
                , ChatTableBeanDao.Properties.TargetId.notEq(ChatApp.getInstance().getUserId())
                , ChatTableBeanDao.Properties.GroupId.isNull(), ChatTableBeanDao.Properties.TargetId.eq(targetId)).list();

    }

    public static List<ChatTableBean> queryByGroupId(String groupId) {
        return DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder().where(
                ChatTableBeanDao.Properties.ChatName.eq(groupId),
                ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT),
                ChatTableBeanDao.Properties.GroupId.eq(groupId),
                ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .orderAsc(ChatTableBeanDao.Properties.MsgTime).list();
    }

    public static List<ChatTableBean> queryByFriendId(String friendId) {
        return DbController.getInstance().getRead().getChatTableBeanDao()
                .queryBuilder().where(
                        ChatTableBeanDao.Properties.ChatName.eq(friendId),
                        ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                        ChatTableBeanDao.Properties.TargetId.eq(friendId),
                        ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .orderAsc(ChatTableBeanDao.Properties.MsgTime).list();
    }

    public static List<ChatTableBean> queryPhotos(String targetId) {
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        return cDao.queryBuilder().where(
                ChatTableBeanDao.Properties.ChatName.eq(targetId)
                , ChatTableBeanDao.Properties.ThumbPath.isNotNull(),
                ChatTableBeanDao.Properties.ChatType.eq(MsgType.Picture))
                .whereOr(
                        ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
                        , ChatTableBeanDao.Properties.GroupId.eq(targetId)
                        , ChatTableBeanDao.Properties.TargetId.eq(targetId),
                        ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId())).list();

    }

    public static List<ChatTableBean> queryUnreadChatList(int fromType, String targetId, String id) {
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        if (fromType == Canstants.GROUP_CHAT) {
            return cDao.queryBuilder().where(
                    ChatTableBeanDao.Properties.ChatName.eq(id),
                    ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT)
                    , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                    , ChatTableBeanDao.Properties.ChatUnRead.eq(ChatTableBean.UNREAD))
                    .whereOr(
                            ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
                            , ChatTableBeanDao.Properties.GroupId.eq(targetId))
                    .orderAsc(ChatTableBeanDao.Properties.MsgTime).list();

        } else {
            return cDao
                    .queryBuilder().where(
                            ChatTableBeanDao.Properties.ChatName.eq(id),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                            ChatTableBeanDao.Properties.ChatUnRead.eq(ChatTableBean.UNREAD),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .orderAsc(ChatTableBeanDao.Properties.MsgTime).list();
        }

    }

//    public static List<ChatTableBean> querySortUnreadChatList(int fromType, String targetId, String id) {
//        List<ChatTableBean> list = queryUnreadChatList(fromType, targetId, id);
//        if (list == null || list.isEmpty()) {
//            return new ArrayList<>();
//        }
//        Collections.sort(list, comparator);
//        return list;
//    }
//
//    public static List<ChatTableBean> querySort(int fromType, String targetId, String id) {
//        List<ChatTableBean> list = query(fromType, targetId, id);
//        if (list == null || list.isEmpty()) {
//            return new ArrayList<>();
//        }
//        Collections.sort(list, comparator);
//        return list;
//    }

    /**
     * 按照时间排序
     */
//    public static Comparator<ChatTableBean> comparator = new Comparator<ChatTableBean>() {
//        @Override
//        public int compare(ChatTableBean o1, ChatTableBean o2) {
//            if (o2.getMsgTime() - o1.getMsgTime() < 0) {
//                return 1;
//            } else if (o2.getMsgTime() - o1.getMsgTime() > 0) {
//                return -1;
//            }
//            return 0;
//        }
//    };
    public static void deleteByGroupId(String groupId) {
        List<ChatTableBean> list = DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder().where(
                ChatTableBeanDao.Properties.ChatName.eq(groupId),
                ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT)
                , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .whereOr(
                        ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
                        , ChatTableBeanDao.Properties.GroupId.eq(groupId)).list();
        if (!CollectionUtils.isEmpty(list))
            delete(list);
    }

    public static void delete(List<ChatTableBean> beanList) {
        try {
            if (beanList == null || beanList.isEmpty()) {
                return;
            }
            ObserverThread.create().onBackGroudThread(new Runnable() {
                @Override
                public void run() {
                    DeleteHistoryUtil.getInstance().deleteFileTable(beanList);
                    for (ChatTableBean chatTableBean : beanList) {
                        delete(chatTableBean);
                    }
                }
            });
//            DbController.getInstance().getWrite().getChatTableBeanDao().deleteInTx(beanList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void delete(ChatTableBean bean) {
        try {
            if (bean == null || bean.id == null) {
                return;
            }
            DbController.getInstance().getWrite().getChatTableBeanDao().delete(bean);
            if (TextUtils.isEmpty(bean.albumId) || Long.valueOf(bean.albumId) < 0) {
                return;
            }
            AlbumManageUtil.deleteFile(bean.getThumbPath());
            AlbumTableBean d = DbController.getInstance().getWrite().getAlbumTableBeanDao().loadByRowId(Long.valueOf(bean.albumId));
            if (d != null) {
                AlbumManageUtil.deleteFile(d.getMPath(), d.getMThumbPath());
            }
            AlbumTableBean.delete(Long.valueOf(bean.albumId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteById(long key) {
        try {
            if (key <= 0L) {
                return;
            }
            ChatTableBean b = DbController.getInstance().getWrite().getChatTableBeanDao().loadByRowId(key);
            delete(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized static void update(ChatTableBean entity) {
        try {
            if (entity.id != null) {
                DbController.getInstance().getWrite().getChatTableBeanDao().update(entity);
            }
//            else {
//                DbController.getInstance().getWrite().getChatTableBeanDao().insertOrReplace(entity);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public synchronized static void updateInx(ChatTableBean entity) {
        try {
            if (entity.id != null) {
                DbController.getInstance().getWrite().getChatTableBeanDao().update(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void update(List<ChatTableBean> list) {
        try {
            DbController.getInstance().getWrite().getChatTableBeanDao().updateInTx(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ChatTableBean getRowItem(String groupId, String targetId, String msgId) {
        if (TextUtils.isEmpty(groupId)) {
            return queryNewFriendMsg(targetId, msgId);
        }
        return queryNewMemberMsg(groupId, targetId, msgId);
    }

    public static ChatTableBean queryNewMemberMsg(String groupId, String targetId, String msgId) {
        try {
            return DbController.getInstance().getRead()
                    .getChatTableBeanDao().queryBuilder().where(
                            ChatTableBeanDao.Properties.ChatName.eq(groupId),
                            ChatTableBeanDao.Properties.GroupId.eq(groupId),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT),
                            ChatTableBeanDao.Properties.MsgId.eq(msgId),
                            ChatTableBeanDao.Properties.ChatUnRead.eq(ChatTableBean.UNREAD),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
//                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .unique();
        } catch (Exception e) {
            return null;
        }
    }

    // =======为不影响别处 查群消息不需要UNREAD 新增方法
    public static ChatTableBean getChatItem(String groupId, String targetId, String msgId) {
        if (TextUtils.isEmpty(groupId)) {
            return queryNewFriendMsg(targetId, msgId);
        }
        return queryNewMemberMsg(groupId, msgId);
    }

    public static ChatTableBean queryNewMemberMsg(String groupId, String msgId) {
        try {
            return DbController.getInstance().getRead()
                    .getChatTableBeanDao().queryBuilder().where(
                            ChatTableBeanDao.Properties.ChatName.eq(groupId),
                            ChatTableBeanDao.Properties.GroupId.eq(groupId),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT),
                            ChatTableBeanDao.Properties.MsgId.eq(msgId),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
//                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .unique();
        } catch (Exception e) {
            return null;
        }
    }

    public static ChatTableBean queryByMessageId(String msgId) {
        ChatTableBean u = DbController.getInstance().getRead()
                .getChatTableBeanDao().queryBuilder().where(
                        ChatTableBeanDao.Properties.MsgId.eq(msgId),
                        ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .unique();
        return u;
    }

    // =======为不影响别处 查群消息不需要UNREAD 新增方法

    public static ChatTableBean queryNewFriendMsg(String targetId, String msgId) {
        ChatTableBean u = DbController.getInstance().getRead()
                .getChatTableBeanDao().queryBuilder().where(
                        ChatTableBeanDao.Properties.ChatName.eq(targetId),
                        ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                        ChatTableBeanDao.Properties.MsgId.eq(msgId),
                        ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId)
//                        , ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                .unique();
        return u;
    }

    public static ChatTableBean queryNewGroupMsg(String targetId, String msgId) {
        ChatTableBean u = DbController.getInstance().getRead()
                .getChatTableBeanDao().queryBuilder().where(
                        ChatTableBeanDao.Properties.GroupId.eq(targetId),
                        ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT),
                        ChatTableBeanDao.Properties.MsgId.eq(msgId),
                        ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .unique();
        return u;
    }

    public static void sort(List<ChatTableBean> list) {
        Collections.sort(list, comparator);
    }

    private static Comparator<ChatTableBean> comparator = new Comparator<ChatTableBean>() {
        @Override
        public int compare(ChatTableBean o1, ChatTableBean o2) {
            if (o2.getHistoryTime() > o1.getHistoryTime()) {
                return -1;
            }
            if (o2.getHistoryTime() < o1.getHistoryTime()) {
                return 1;
            }
            return 0;
        }
    };


    public String getLoginUserId() {
        return this.loginUserId;
    }

    public void setLoginUserId(String loginUserId) {
        this.loginUserId = loginUserId;
    }

    public String getTargetFileId() {
        return this.targetFileId;
    }

    public void setTargetFileId(String targetFileId) {
        this.targetFileId = targetFileId;
    }

    public String getGroupType() {
        return this.groupType;
    }

    public void setGroupType(String groupType) {
        this.groupType = groupType;
    }

    public String getChatName() {
        return this.chatName;
    }

    public void setChatName(String chatName) {
        this.chatName = chatName;
    }

    public String getThumbPath() {
        return this.thumbPath;
    }

    public void setThumbPath(String thumbPath) {
        this.thumbPath = thumbPath;
    }

    public boolean getStartReadFinish() {
        return this.startReadFinish;
    }

    public long getFileLength() {
        return this.fileLength;
    }

    public void setFileLength(long fileLength) {
        this.fileLength = fileLength;
    }


    public String getChatAvatarPath() {
        return this.chatAvatarPath;
    }

    public void setChatAvatarPath(String chatAvatarPath) {
        this.chatAvatarPath = chatAvatarPath;
    }

    public static long queryUnreadChatCount(int fromType, String targetId) {
        if (TextUtils.isEmpty(targetId)) {
            return 0;
        }
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        if (fromType == Canstants.GROUP_CHAT) {
            return cDao.queryBuilder().where(
                    ChatTableBeanDao.Properties.ChatName.eq(targetId),
                    ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT)
                    , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                    , ChatTableBeanDao.Properties.ChatUnRead.eq(ChatTableBean.UNREAD))
//                    .whereOr(
//                            ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
//                            , ChatTableBeanDao.Properties.GroupId.eq(targetId))
                    .count();

        } else {
            return cDao
                    .queryBuilder().where(
                            ChatTableBeanDao.Properties.ChatName.eq(targetId),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                            ChatTableBeanDao.Properties.ChatUnRead.eq(ChatTableBean.UNREAD),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
//                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .count();
        }

    }

    public static long queryChatCount(int fromType, String targetId) {
        if (TextUtils.isEmpty(targetId)) {
            return 0;
        }
        ChatTableBeanDao cDao = DbController.getInstance().getRead().getChatTableBeanDao();
        if (fromType == Canstants.GROUP_CHAT) {
            return cDao.queryBuilder().where(
                    ChatTableBeanDao.Properties.ChatName.eq(targetId),
                    ChatTableBeanDao.Properties.FromType.eq(Canstants.GROUP_CHAT)
                    , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(
//                            ChatTableBeanDao.Properties.GroupId.eq(ChatApp.getInstance().getUserId())
//                            , ChatTableBeanDao.Properties.GroupId.eq(targetId))
                    .count();

        } else {
            return cDao
                    .queryBuilder().where(
                            ChatTableBeanDao.Properties.ChatName.eq(targetId),
                            ChatTableBeanDao.Properties.FromType.eq(Canstants.SINGLE_CHAT),
                            ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
//                    .whereOr(ChatTableBeanDao.Properties.TargetId.eq(targetId),
//                            ChatTableBeanDao.Properties.TargetId.eq(ChatApp.getInstance().getUserId()))
                    .count();
        }

    }

    public static long queryCount(int fromType, String targetId) {
        if (TextUtils.isEmpty(targetId)) {
            return 0;
        }
        //  , ChatTableBeanDao.Properties.ChatType.ge(MsgType.History_Time)
        return DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.ChatName.eq(targetId), ChatTableBeanDao.Properties.FromType.eq(fromType)
                        , ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .count();


    }

    public static void updateFriendAvatar(String friendUserId, String avatarUrl) {
        List<ChatTableBean> list = DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.TargetId.eq(friendUserId),
                        ChatTableBeanDao.Properties.TargetId.notEq(ChatApp.getInstance().getUserId()),
                        ChatTableBeanDao.Properties.ChatAvatarUrl.notEq(avatarUrl),
                        ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            for (ChatTableBean chatTableBean : list) {
                chatTableBean.setChatAvatarPath(null);
                chatTableBean.setChatAvatarUrl(avatarUrl);
            }
            DbController.getInstance().getWrite().getChatTableBeanDao().updateInTx(list);
        }
    }

    public static void updateGroupMemberAvatar(String groupId, String memberId, String avatarUrl) {
        updateFriendAvatar(memberId, avatarUrl);
    }

    public int getVoiceListen() {
        return this.voiceListen;
    }

    public void setVoiceListen(int voiceListen) {
        this.voiceListen = voiceListen;
    }

    public Long getRelateId() {
        return this.relateId;
    }

    public void setRelateId(Long relateId) {
        this.relateId = relateId;
    }

    public String getAlias() {
        return this.alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getAtelIds() {
        return this.atelIds;
    }

    public void setAtelIds(String atelIds) {
        this.atelIds = atelIds;
    }

    @Override
    public String toString() {
        return "ChatTableBean{" +
                "id=" + id +
                ", fromType=" + fromType +
                ", groupId='" + groupId + '\'' +
                ", groupType='" + groupType + '\'' +
                ", targetFileId='" + targetFileId + '\'' +
                ", targetId='" + targetId + '\'' +
                ", targetName='" + targetName + '\'' +
                ", targetType='" + targetType + '\'' +
                ", nickName='" + nickName + '\'' +
                ", alias='" + alias + '\'' +
                ", chatAvatarUrl='" + chatAvatarUrl + '\'' +
                ", chatAvatarPath='" + chatAvatarPath + '\'' +
                ", chatAvatarId='" + chatAvatarId + '\'' +
                ", chatType=" + chatType +
                ", chatUnRead=" + chatUnRead +
                ", historyTime=" + historyTime +
                ", msgTime=" + msgTime +
                ", textMsg='" + textMsg + '\'' +
                ", fileUrl='" + fileUrl + '\'' +
                ", thumbPath='" + thumbPath + '\'' +
                ", fileLength=" + fileLength +
                ", albumId='" + albumId + '\'' +
                ", sendType=" + sendType +
                ", msgId='" + msgId + '\'' +
                ", loginUserId='" + loginUserId + '\'' +
                ", chatName='" + chatName + '\'' +
                ", startReadFinish=" + startReadFinish +
                ", readFinishTime=" + readFinishTime +
                ", sendState=" + sendState +
                ", voiceListen=" + voiceListen +
                ", relateId=" + relateId +
                ", atelIds='" + atelIds + '\'' +
                ", isChecked=" + isChecked +
                ", isVisible=" + isVisible +
                '}';
    }

    public static String regularClearance(String id, long timeMillis) {
        List<ChatTableBean> list = DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.TargetId.eq(id), ChatTableBeanDao.Properties.SendType.eq(ChatTableBean.RECEIVE), ChatTableBeanDao.Properties.HistoryTime.le(timeMillis))
                .where(ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()))
                .list();
        DeleteHistoryUtil.getInstance().deleteFileTable(list);
        StringBuilder idsBuilder = new StringBuilder();
        for (ChatTableBean chatTableBean : list) {
            idsBuilder.append(",").append(chatTableBean.getId());
            delete(chatTableBean);
            if (chatTableBean.getRelateId() != null && chatTableBean.getRelateId() > 0) {
                idsBuilder.append(",").append(chatTableBean.getRelateId());
                deleteHistoryTime(chatTableBean.getRelateId());
            }
        }
        if (idsBuilder.length() > 0)
            idsBuilder.deleteCharAt(0);
        return idsBuilder.toString();
    }

    public static void deleteHistoryTime(Long id) {
        if (id == null || id <= 0)
            return;
        DbController.getInstance().getWrite().getChatTableBeanDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.ChatType.eq(MsgType.History_Time), ChatTableBeanDao.Properties.Id.eq(id))
                .buildDelete().executeDeleteWithoutDetachingEntities();
    }
}
